import React, {useEffect} from 'react';
import { forwardRef, useState, useRef } from 'react';
import './index.scss';
import * as echarts from "echarts";

export interface AlertTab {
  id: string;
  text: string;
  isActive?: boolean;
  onClick?: () => void;
}

export interface AlertRecord {
  id: string;
  location: string;
  time: string;
  details: string;
  isHighlighted?: boolean;
}

export interface EmergencyAlertProps {
  width?: string | number;
  height?: string | number;
  iconImage?: string;
  iconSize?: {
    width?: number;
    height?: number;
  };
  tabs?: AlertTab[];
  headerBackgroundImage?: string;
  tableHeaderBackgroundImage?: string;
  tableRowBackgroundImage?: string;
  records?: AlertRecord[];
  showTextShadow?: boolean;
  headerLabels?: {
    location?: string;
    time?: string;
    details?: string;
  };
  onTabClick?: (tab: AlertTab, index: number) => void;
  onRecordClick?: (record: AlertRecord, index: number) => void;
  theme?: 'light' | 'dark';
  style?: React.CSSProperties;
  className?: string;
  onClick?: () => void;
  __designMode?: string;
  componentId?: string;
  _componentName?: string;
  forwardRef?: any;
}

const EmergencyAlert = forwardRef<HTMLDivElement, EmergencyAlertProps>((props, ref) => {
  const {
    width = 500,
    height = 1080,
    title = '应急预警与响应',
    subtitle = 'Emergency early warn',
    iconImage = 'http://localhost:8085/static/images/yingjiguanli/bz5.png',
    iconSize = {
      width: 20,
      height: 20
    },
    headerTextColor = '#56A5FF',
    recordTextColor = 'rgba(255,255,255,0.9)',
    tabs = [
      { id: 'tab1', text: '月', isActive: true },
      { id: 'tab2', text: '年', isActive: false }
    ],
    topTabs = [
      { id: '1', text: '穿越围栏', isActive: true },
      { id: '2', text: '拌线入侵', isActive: false },
      { id: '3', text: '区域入侵', isActive: false },
      { id: '4', text: '物品遗留', isActive: false },
      { id: '5', text: '遗留XX', isActive: false },
      { id: '6', text: '56343', isActive: false },
    ],
    headerBackgroundImage = 'http://localhost:8085/static/images/yingjiguanli/dhan.png',
    tableHeaderBackgroundImage = 'http://localhost:8085/static/images/yingjiguanli/bz6.png',
    tableRowBackgroundImage = 'http://localhost:8085/static/images/yingjiguanli/Frame26.png',
    cameras = [
      { id: '1', name: '监控1', isActive: true, hasSignal: true },
      { id: '2', name: '监控2', isActive: false, hasSignal: true },
      { id: '3', name: '监控3', isActive: false, hasSignal: false },
      { id: '4', name: '监控4', isActive: false, hasSignal: true }
    ],
    mainBackgroundImage = 'http://localhost:8085/static/images/changjingjiankong/bz44.png',
    tableHeaders = [
      { key: 'title', value: '事件名称', width: '25' },
      { key: 'month', value: '时间', width: '15' },
      { key: 'type', value: '当前状态', width: '15' },
      { key: 'address', value: '位置', width: '32' },
      { key: 'expiring', value: '等级', width: '13' },
    ],
    records = [
      { id: '1', title: '事件名称', month: '07-01', address: '华阳老街是这里呀', type: '问题分类',  expiring: '一级'},
      { id: '2', title: '事件名称', month: '07-02', address: '地址', type: '问题分类', expiring: '一级' },
      { id: '3', title: '事件名称', month: '07-03', address: '地址', type: '问题分类', expiring: '一级' },
      { id: '4', title: '事件名称', month: '07-04', address: '地址', type: '问题分类', expiring: '一级' },
      { id: '5', title: '事件名称', month: '07-04', address: '地址', type: '问题分类', expiring: '一级' },
      { id: '6', title: '事件名称', month: '07-04', address: '地址', type: '问题分类', expiring: '一级' },
      { id: '7', title: '事件名称', month: '07-04', address: '地址', type: '问题分类', expiring: '一级' },
      { id: '8', title: '事件名称', month: '07-04', address: '地址', type: '问题分类', expiring: '一级' },
      { id: '9', title: '事件名称', month: '07-04', address: '地址', type: '问题分类', expiring: '一级' },
    ],
    showTextShadow = true,
    headerLabels = {
      location: '监控位置',
      time: '监控时间',
      details: '告警详情'
    },
    onTabClick,
    onRecordClick,
    theme = 'dark',
    style = {},
    className = '',
    onClick,
    __designMode,
    componentId,
    _componentName,
    forwardRef: forwardRefProp,
    ...otherProps
  } = props;

  const componentStyle: React.CSSProperties = {
    width: typeof width === 'number' ? `${width}px` : width,
    height: typeof height === 'number' ? `${height}px` : height,
    ...style
  };
  const [scrollPosition, setScrollPosition] = useState(0);
  const [tabIndex, setTabIndex] = useState(0)
  const tabContainerRef = useRef<HTMLDivElement | null>(null);
  const chartRef = useRef<HTMLDivElement>(null);
  const [activeTabIndex, setActiveTabIndex] = useState(0);
  const myChartData = {
    vehicleFlow: [120, 132, 101, 134, 90, 230],
    passengerFlow: [220, 182, 191, 234, 290, 330],
  }
  useEffect(() => {
    if (chartRef.current && myChartData) {
      const chartInstance = echarts.init(chartRef.current);
      const option = {
        color: '#0091FF',
        grid: {
          left: '10%',
          right: 0,
          top: '15%',
          bottom: '12%',
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(255,255,255,0.2)',
            },
          },
          axisLabel: {
            fontSize: 14,
            color: 'rgba(255, 255, 255, 0.80)',
            interval: 1,
            margin: 10
          },
          data: ['昨日早间', '昨日晚间', '昨日夜间', '今日早间', '今日晚间', '今日夜间'],

        },
        yAxis: {
          type: 'value',
          splitNumber: 4,
          axisLabel: {
            fontSize: 12,
            color: 'rgba(255, 255, 255, 0.80)',
            interval: 1
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: 'rgba(255,255,255,0.1)',
            },
          }
        },
        series: [
          {
            name: '车辆时点客流',
            type: 'line',
            data: myChartData.vehicleFlow,
            symbol: 'none',
            smooth: true
          }
        ],
      };
      chartInstance.setOption(option);
      window.addEventListener('resize', () => chartInstance.resize());
      return () => {
        chartInstance.dispose();
      };
    }
  }, [myChartData]);

  const handleTabClick = (tab: AlertTab, index: number) => {
    setTabIndex(index)
    if (onTabClick) {
      onTabClick(tab, index);
    }
  };

  const handleRecordClick = (record: AlertRecord, index: number) => {
    if (onRecordClick) {
      onRecordClick(record, index);
    }
  };
  const handleLeftClick = () => {
    if (tabContainerRef.current) {
      const newScrollLeft = tabContainerRef.current.scrollLeft - 200;
      tabContainerRef.current.scrollTo({
        left: Math.max(newScrollLeft, 0),
        behavior: 'smooth'
      });
    }
  };
  const handleMainAreaClick = () => {
  };
  const handleRightClick = () => {
    if (tabContainerRef.current) {
      const newScrollLeft = tabContainerRef.current.scrollLeft + 200;
      const maxScrollLeft = tabContainerRef.current.scrollWidth - tabContainerRef.current.clientWidth;
      tabContainerRef.current.scrollTo({
        left: Math.min(newScrollLeft, maxScrollLeft),
        behavior: 'smooth'
      });
    }
  };

  const emergencyAlertClassName = ['emergency-alert', theme, className].filter(Boolean).join(' ');

  return (
    <div
      ref={ref}
      className={emergencyAlertClassName}
      style={componentStyle}
      onClick={onClick}
      data-component-id={componentId}
      data-component-name={_componentName}
      data-design-mode={__designMode}
      {...otherProps}
    >
      <div className="title-wrap" style={{backgroundImage: 'url(http://localhost:8085/static/images/zonghezhifa/title-bg.png)'}}>
        <div className="title-str">
          <div className="title">
            <div>{title}</div>
            <div className="sen-title">{title}</div>
          </div>
          <div className="subtitle">{subtitle}</div>
        </div>
      </div>
      <div className="content-wrap">
        <div className="alert-tabs">
          {/* 左箭头 */}
          <div
            className="alert-icon"
            style={{
              width: `${iconSize.width}px`,
              height: `${iconSize.height}px`,
              backgroundImage: iconImage ? `url(${iconImage})` : undefined
            }}
            onClick={handleLeftClick}
          />
          <div className="tabs-scroll"
               ref={tabContainerRef}
               style={{transition: 'scroll-behavior 0.3s ease'}}>
            {/* 标签按钮 */}
            {topTabs.map((tab, index) => (
              <div
                key={tab.id}
                className={`alert-tab ${tabIndex === index ? 'active' : 'unactive'}`}
                style={{
                  backgroundImage: tabIndex === index ? `url(http://localhost:8085/static/images/yingjiguanli/tab-active.png)` : 'url(http://localhost:8085/static/images/yingjiguanli/tab-un-active.png)',
                }}
                onClick={() => handleTabClick(tab, index)}
              >
                <span style={{color: tabIndex === index ? 'rgba(255,255,255,1)' : 'rgba(255,255,255,0.8)'}}>{tab.text}</span>
              </div>
            ))}
          </div>
          {/* 右侧箭头 */}
          <div
            className="alert-icon"
            style={{
              width: `${iconSize.width}px`,
              height: `${iconSize.height}px`,
              backgroundImage: 'url(static/images/yingjiguanli/right-icon.png)'
            }}
            onClick={handleRightClick}
          />
        </div>
        <div className="table-area">
          {/* 表头 */}
          <div className="table-header" style={{backgroundImage:`url(http://localhost:8085/static/images/qixiangfangzhai/bz54.png)`}}>
            {tableHeaders.map((head,value) => (
              <div
                className="header-cell"
                style={{ color: headerTextColor, width: `${head.width}%` }}
              >
                {head.value}
              </div>
            ))}
          </div>
          {/* 表格数据 */}
          <div className="table-body"  style={{height: 'calc(100% - 40px)'}}>
            {records.map((record, index) => (
              <div
                key={record.id}
                className="table-row"
              >
                {tableHeaders.map((head) => (
                  <div
                    className="table-cell"
                    style={{ color: recordTextColor, width: `${head.width}%` }}
                  >
                    {record[head.key]}
                  </div>
                ))}
              </div>
            ))}
          </div>
        </div>
        <div className="chart-area">
          <div className="tab-selector">
            {tabs.map((tab, index) => (
              <div
                key={tab.id}
                className={`tab-item ${activeTabIndex === index ? 'isActive' : 'unActive'}`}
                onClick={() => handleTimeSelectorClick(tab, index)}
              >
                {tab.text}
              </div>
            ))}
          </div>
          <div className="chart-container" ref={chartRef} style={{ width: '100%', height: '203px' }}>
          </div>
        </div>
        <div className="item-head">
          <div className="head-round" style={{backgroundImage: 'url(static/images/zonghezhifa/point-icon-blue.png)'}} />
          <div className="head-title">场景监控</div>
          <div className="head-line" />
          <div className="head-right" style={{backgroundImage: 'url(static/images/zonghezhifa/left-icon-blue.png)'}} />
          <div className="plus-icon" style={{backgroundImage: 'url(static/images/zonghezhifa/plus-icon.png)'}} />
        </div>
        <div className="video-area">
          <select className="select-wrap">
            {cameras.map((c, index) => (
              <option key={c.id} value={c.id}>{c.name}</option>
            ))}
          </select>
          {/* 主监控区域 */}
          <div
            className="video-wrap"
            style={{
              backgroundImage: mainBackgroundImage ? `url(${mainBackgroundImage})` : undefined
            }}
            onClick={handleMainAreaClick}
          >
            {/* 监控内容占位 */}
            <video className="video-content" controls autoPlay>
              <source src="https://www.runoob.com/try/demo_source/movie.mp4" type="video/mp4"/>
            </video>
            <div className="video-str">视频上的叠加内容</div>
            {/* 监控信息叠加层 */}
          </div>
        </div>
      </div>
      <div className="bottom-line" />
    </div>
  );
});

EmergencyAlert.displayName = 'EmergencyAlert';

export default EmergencyAlert;
